package com.sp2p.service.admin;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.ContextLoader;

import sun.management.resources.agent;

import com.sp2p.dao.BorrowDao;
import com.sp2p.dao.NoticeTaskDao;
import com.sp2p.dao.OperationLogDao;
import com.sp2p.dao.RepaymentRecordDao;
import com.sp2p.dao.FundRecordDao;
import com.sp2p.dao.UserDao;
import com.shove.Convert;
import com.shove.base.BaseService;
import com.shove.data.DataException;
import com.shove.data.DataSet;
import com.shove.data.dao.MySQL;
import com.shove.vo.PageBean;
import com.sp2p.constants.IAmountConstants;
import com.sp2p.constants.IConstants;
import com.sp2p.constants.IInformTemplateConstants;
import com.sp2p.dao.AccountUsersDao;
import com.sp2p.dao.InvestDao;
import com.sp2p.dao.RepamentDao;
import com.sp2p.dao.admin.AdminDao;
import com.sp2p.dao.admin.BorrowManageDao;
import com.sp2p.database.Dao.Procedures;
import com.sp2p.database.Dao.Views.intentionfund_user;
import com.sp2p.service.AwardService;
import com.sp2p.service.SelectedService;
import com.sp2p.util.AmountUtil;

/**
 * @ClassName: BorrowManageService.java
 * @Author: gang.lv
 * @Date: 2013-3-10 下午10:07:28
 * @Copyright: 2013 www.emis.com Inc. All rights reserved.
 * @Version: V1.0.1
 * @Descrb: 后台借款管理业务处理
 */
public class BorrowManageService extends BaseService {

	public static Log log = LogFactory.getLog(BorrowManageService.class);

	private BorrowManageDao borrowManageDao;
	private SelectedService selectedService;
	private AwardService awardService;
	private InvestDao investDao;
	private AccountUsersDao accountUsersDao;
	private RepamentDao repamentDao;
	private UserDao userDao;
	private FundRecordDao fundRecordDao;
	private RepaymentRecordDao repaymentRecordDao;
	private AdminDao adminDao;
	private BorrowDao borrowDao;
	private PlatformCostService platformCostService;
	private NoticeTaskDao noticeTaskDao;
	private OperationLogDao operationLogDao;

	/**
	 * @MethodName: queryAllCirculationRepayRecordByCondition
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-5-23 下午11:24:18
	 * @Return:
	 * @Descb: 根据条件查询流转标还款记录
	 * @Throws:
	 */
	public void queryAllCirculationRepayRecordByCondition(String userName,
			int borrowStatus, String borrowTitle,
			PageBean<Map<String, Object>> pageBean) throws Exception {
		String resultFeilds = " a.*";
		StringBuffer condition = new StringBuffer();
		if (StringUtils.isNotBlank(userName)) {
			condition.append(" and a.username  LIKE CONCAT('%','"
					+ StringEscapeUtils.escapeSql(userName.trim()) + "','%')");
		}
		if (StringUtils.isNotBlank(borrowTitle)) {
			condition.append(" and a.borrowTitle  LIKE CONCAT('%','"
					+ StringEscapeUtils.escapeSql(borrowTitle.trim())
					+ "','%')");
		}
		if (IConstants.DEFAULT_NUMERIC != borrowStatus) {
			condition.append(" and borrowStatus =" + borrowStatus);
		}
		Connection conn = MySQL.getConnection();
		try {
			dataPage(conn, pageBean, " v_t_circulation_repayrecord a",
					resultFeilds, " order by a.id asc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: updateBorrowCirculationStatus
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-5-20 下午03:21:21
	 * @Return:
	 * @Descb: 更新流转标状态
	 * @Throws:
	 */
	public long updateBorrowCirculationStatus(long borrowId, long reciverId,
			long statusLong, String auditOpinion, Long adminId,
			String basePath, Map<String, Object> platformCostMap)
			throws Exception {
		Connection conn = MySQL.getConnection();
		int circulationStatus = -1;
		double borrowSum = 0;
		double yearRate = 0;
		int deadline = 0;
		int isDayThe = 1;
		Long result = -1L;
		try {
			Map<String, String> borrowMap = borrowManageDao.queryBorrowInfo(
					conn, borrowId);
			if (borrowMap == null)
				borrowMap = new HashMap<String, String>();
			borrowSum = Convert.strToDouble(borrowMap.get("borrowAmount") + "",
					0);
			yearRate = Convert.strToDouble(borrowMap.get("annualRate") + "", 0);
			deadline = Convert.strToInt(borrowMap.get("deadline") + "", 0);
			isDayThe = Convert.strToInt(borrowMap.get("isDayThe") + "", 1);
			// 处理流转标
			result = borrowManageDao.updateBorrowCirculationStatus(conn,
					borrowId, statusLong, auditOpinion, circulationStatus, 10);
			if (result > 0) {
				// 审核通过添加还款记录
				if (statusLong == 2) {
					AmountUtil au = new AmountUtil();
					List<Map<String, Object>> rateCalculateOneList = au
							.rateCalculateOne(borrowSum, yearRate, deadline,
									isDayThe);
					for (Map<String, Object> oneMap : rateCalculateOneList) {
						String repayPeriod = oneMap.get("repayPeriod") + "";
						String repayDate = oneMap.get("repayDate") + "";
						// 添加还款记录,还款金额和利息在投资时进行累加
						result = borrowManageDao.addRepayRecord(conn,
								repayPeriod, 0, 0, borrowId, 0, 0, repayDate);
					}
				}
			}
			if (result <= 0) {
				conn.rollback();
				return -1L;
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return result;
	}

	/**
	 * @MethodName: queryBorrowCirculationDetailById
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-5-20 下午02:52:55
	 * @Return:
	 * @Descb: 查询流转标详情
	 * @Throws:
	 */
	public Map<String, String> queryBorrowCirculationDetailById(long id)
			throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowCirculationDetailById(conn, id);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	/**
	 * @MethodName: queryCirculationRepayRecord
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-7-23 下午07:37:39
	 * @Return:
	 * @Descb: 查询流转标还款记录
	 * @Throws:
	 */
	public List<Map<String, Object>> queryCirculationRepayRecord(long borrowId)
			throws Exception {
		Connection conn = MySQL.getConnection();
		List<Map<String, Object>> list = null;
		try {
			list = borrowManageDao.queryCirculationRepayRecord(conn, borrowId);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return list;
	}

	/**
	 * @MethodName: queryAllCirculationByCondition
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-5-20 上午11:37:27
	 * @Return:
	 * @Descb: 查询流转标借款
	 * @Throws:
	 */
	public void queryAllCirculationByCondition(String userName, int borrowWay,
			int borrowStatus, String undertaker,
			PageBean<Map<String, Object>> pageBean) throws Exception {
		String resultFeilds = " a.*,b.userid,b.counts,c.userName as undertakerName ";
		StringBuffer condition = new StringBuffer();
		if (StringUtils.isNotBlank(userName)) {
			condition.append(" and a.username  LIKE CONCAT('%','"
					+ StringEscapeUtils.escapeSql(userName.trim()) + "','%')");
		}
		if (StringUtils.isNotBlank(undertaker)) {
			condition
					.append(" and c.userName  LIKE CONCAT('%','"
							+ StringEscapeUtils.escapeSql(undertaker.trim())
							+ "','%')");
		}
		if (IConstants.DEFAULT_NUMERIC != borrowStatus) {
			condition.append(" and a.borrowStatus =" + borrowStatus);
		}
		condition.append(" and a.borrowShow=2");
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" v_t_borrow_circulation a LEFT JOIN (SELECT userid,COUNT(1) AS counts FROM t_materialsauth where auditStatus = 3 GROUP BY userid) b ON a.userid=b.userid"
							+ " left join t_admin c on a.undertaker=c.id",
					resultFeilds, " order by a.borrowStatus asc,a.id desc",
					condition.toString());
			conn.commit();
			
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: queryBorrowFistAuditByCondition
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:09:16
	 * @Return:
	 * @Descb: 查询后台借款管理中的初审借款记录(待发布)
	 * @Throws:
	 */
	public void queryBorrowFistAuditByCondition(String userName, int borrowWay,
			PageBean<Map<String, Object>> pageBean) throws Exception {
		String resultFeilds = " * ";
		StringBuffer condition = new StringBuffer();

		if (StringUtils.isNotBlank(userName)) {
			condition.append(" and username  like '%"
					+ StringEscapeUtils.escapeSql(userName.trim()) + "%' ");
		}
		if (IConstants.DEFAULT_NUMERIC != borrowWay) {
			condition.append(" and t.borrowWayYTF =" + borrowWay);
		}

		String filed = " a.*,b.counts";

		String table = "(select  "
				+ filed
				+ " from v_t_borrow_h_firstaudit a LEFT JOIN (SELECT userid,COUNT(1) AS counts FROM t_materialsauth where auditStatus = 3 GROUP BY userid) b ON a.userId=b.userid "
				+ " INNER JOIN v_t_user_approve_lists c on a.userId = c.uid where a.borrowWay >2  "
				+ "UNION ALL SELECT  "
				+ filed
				+ " from v_t_borrow_h_firstaudit a LEFT JOIN (SELECT userid,COUNT(1) AS counts FROM t_materialsauth "
				+ "where auditStatus = 3  GROUP BY userid) b ON a.userId=b.userid   "
				+ "INNER JOIN v_t_user_base_approve_lists d  on a.userId=d.uuid where d.auditStatus=3) t ";
		// ----
		Connection conn = MySQL.getConnection();
		try {
			// 秒还净值个人资料通过审核即可 其它借款需要个人资料+工作认证+5项基本认证
			dataPage(conn, pageBean, table,
			// ---
					resultFeilds, " group by id order by id desc ", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * add by houli 查询等待资料审核的数据
	 * 
	 * @param userName
	 * @param borrowWay
	 * @param pageBean
	 * @throws Exception
	 * @throws DataException
	 */
	public void queryBorrowWaitingAuditByCondition(String userName,
			int borrowWay, PageBean<Map<String, Object>> pageBean)
			throws Exception {
		String resultFeilds = " * ";
		StringBuffer condition = new StringBuffer();

		if (StringUtils.isNotBlank(userName)) {
			condition.append(" and username  like '%"
					+ StringEscapeUtils.escapeSql(userName.trim()) + "%' ");
		}
		if (IConstants.DEFAULT_NUMERIC != borrowWay) {
			condition.append(" and borrowWay =" + borrowWay);
		}
		String filed = "a.id,a.userId,a.username,a.realName,b.counts as counts,a.borrowWay,a.borrowTitle,"
				+ "a.borrowAmount,a.annualRate,a.deadline,a.raiseTerm,a.isDayThe ,a.borrowShow";
		String table = " (select  "
				+ filed
				+ " from v_t_borrow_h_firstaudit a LEFT JOIN (SELECT userid,COUNT(1) AS counts FROM t_materialsauth where auditStatus = 3 GROUP BY userid) b ON a.userId=b.userid "

				+ " inner join v_t_user_un_approve_lists c on a.userid = c.uid where a.borrowway >2 "
				+ "union all select  "
				+ filed
				+ " from v_t_borrow_h_firstaudit a left join (select userid,count(1) as counts from t_materialsauth "
				+ "where auditstatus = 3  group by userid) b on a.userid=b.userid   "
				+ "inner join v_t_user_base_approve_lists d  on a.userid=d.uuid where a.borrowway <3 and d.auditstatus!=3) t";

		Connection conn = MySQL.getConnection();
		try {
			// 秒还净值个人资料通过审核即可 其它借款需要个人资料+工作认证+5项基本认证
			dataPage(conn, pageBean, table, resultFeilds, "order by  id desc ",
					condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: queryBorrowFistAuditDetailById
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:24:35
	 * @Return:
	 * @Descb: 后台借款待发布的借款详情
	 * @Throws:
	 */
	public Map<String, String> queryBorrowFistAuditDetailById(long id)
			throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowFistAuditDetailById(conn, id);
			map.put("mailContent", "");
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}
	
	/**
	 * @MethodName: queryBorrowTenderInByCondition
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:09:16
	 * @Return:
	 * @Descb: 查询后台借款管理中的待发布借款记录
	 * @Throws:
	 */
	public void queryBorrowWaitPublishCondition(String userName, int borrowWay,
			PageBean<Map<String, Object>> pageBean) throws Exception {
		String resultFeilds = " * ";
		StringBuffer condition = new StringBuffer();
		if (StringUtils.isNotBlank(userName)) {
			condition.append(" and username  like '%"
					+ StringEscapeUtils.escapeSql(userName.trim()) + "%' ");
		}
		if (IConstants.DEFAULT_NUMERIC != borrowWay) {
			condition.append(" and borrowWay =" + borrowWay);
		}
		condition.append(" and borrowStatus = 1");
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					"v_t_borrow_detail",
					resultFeilds, " order by id desc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: queryBorrowTenderInByCondition
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:09:16
	 * @Return:
	 * @Descb: 查询后台借款管理中的招标中借款记录
	 * @Throws:
	 */
	public void queryBorrowTenderInByCondition(String userName, int borrowWay,
			PageBean<Map<String, Object>> pageBean) throws Exception {
		String resultFeilds = " * ";
		StringBuffer condition = new StringBuffer();
		if (StringUtils.isNotBlank(userName)) {
			condition.append(" and username  like '%"
					+ StringEscapeUtils.escapeSql(userName.trim()) + "%' ");
		}
		if (IConstants.DEFAULT_NUMERIC != borrowWay) {
			condition.append(" and borrowWayYTF =" + borrowWay);
		}
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" v_t_borrow_h_tenderin a LEFT JOIN (SELECT userid,COUNT(1) AS counts FROM t_materialsauth where auditStatus = 3 GROUP BY userid) b ON a.userid=b.userid ",
					resultFeilds, " order by id desc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: queryBorrowTenderInDetailById
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:24:35
	 * @Return:
	 * @Descb: 后台借款招标中的借款详情
	 * @Throws:
	 */
	public Map<String, String> queryBorrowTenderInDetailById(long id)
			throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> mapNotick = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowTenderInDetailById(conn, id);
			if (map != null) {
				long userId = Convert.strToLong(map.get("userId"), -1L);
				mapNotick = noticeTaskDao.queryNoticeTask(conn, userId, id);
				
				if (mapNotick == null) {
					Map<String, String> maps = noticeTaskDao
							.queryNoticeTasklog(conn, userId, id);
					String mail_info="";
					if(maps!=null&&maps.get("mail_info")!=null&&maps.get("mail_info").length()>0){
						mail_info=Convert.strToStr(maps.get("mail_info"),"");
					}
					map.put("mailContent", 	mail_info+ "");
				} else {
					map.put("mailContent", Convert.strToStr(mapNotick
							.get("mail_info")
							+ "", ""));
				}
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	/**
	 * @MethodName: queryBorrowFullScaleByCondition
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:09:16
	 * @Return:
	 * @Descb: 查询后台借款管理中的满标借款记录
	 * @Throws:
	 */
	public void queryBorrowFullScaleByCondition(Long id,String userName, int borrowWayYTF, int borrowProduct,int agent,
			PageBean<Map<String, Object>> pageBean) throws Exception {
		String resultFeilds = " * , f_sjzd('productType',borrowProduct) borrowProductRename ," +
				" f_sjzd('borrowWayType', borrowWayYTF) borrowWayYTFRename ," +
				" CONCAT(annualRate ,'%')  annualRateRename ," + 
				" CASE WHEN isDayThe = 1 THEN CONCAT(deadline, '个月') ELSE CONCAT(deadline, '天') END AS deadlineRename ," +
				" CONCAT(raiseTerm ,'天')  raiseTermRename ," +
				" CONCAT(jbScore ,'分')  jbScoreRename ," +
				" CONCAT(xyScore ,'分')  xyScoreRename ," +
				" CONCAT(zcScore ,'分')  zcScoreRename ," +
				" CONCAT(allScore ,'分')  allScoreRename ," +
				" f_sjzd('borrowStatusType', borrowStatus) borrowStatusRename ," +
				" f_sjzd('paymentModeType', borrowWayYTF) paymentModeTypeRename ";
		StringBuffer condition = new StringBuffer();
		if (id > 0) {
			condition.append(" and parentBId =" + id);
		}
		if (StringUtils.isNotBlank(userName)) {
			condition.append(" and username  like '%"
					+ StringEscapeUtils.escapeSql(userName.trim()) + "%' ");
		}
		if (borrowWayYTF > 0) {
			condition.append(" and borrowWayYTF =" + borrowWayYTF);
		}
		if (borrowProduct > 0) {
			condition.append(" and borrowProduct =" + borrowProduct);
		}
		if (agent > 0){
			condition.append(" and agent =" + agent);
		}
		
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" v_t_borrow_h_fullscale a LEFT JOIN (SELECT userid,COUNT(1) AS counts FROM t_materialsauth where auditStatus = 3 GROUP BY userid) b ON a.userid=b.userid ",
					resultFeilds, " order by id desc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: queryBorrowFullScaleDetailById
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:24:35
	 * @Return:
	 * @Descb: 后台借款满标的借款详情
	 * @Throws:
	 */
	public Map<String, String> queryBorrowFullScaleDetailById(long id)
			throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> mapNotick = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowFullScaleDetailById(conn, id);
			if (map != null) {
				long userId = Convert.strToLong(map.get("userId"), -1L);
				mapNotick = noticeTaskDao.queryNoticeTask(conn, userId, id);
				/*if (mapNotick == null) {
					Map<String, String> maps = noticeTaskDao
							.queryNoticeTasklog(conn, userId, id);
					map.put("mailContent", Convert.strToStr(maps
							.get("mail_info")
							+ "", ""));
				} else {
					map.put("mailContent", Convert.strToStr(mapNotick
							.get("mail_info")
							+ "", ""));
				}*/

			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	/**
	 * @MethodName: queryBorrowFlowMarkByCondition
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:09:16
	 * @Return:
	 * @Descb: 查询后台借款管理中的流标借款记录
	 * @Throws:
	 */
	public void queryBorrowFlowMarkByCondition(String userName, int borrowWay,
			PageBean<Map<String, Object>> pageBean) throws Exception {
		String resultFeilds = " * ";
		StringBuffer condition = new StringBuffer();
		if (StringUtils.isNotBlank(userName)) {
			condition.append(" and username  like '%"
					+ StringEscapeUtils.escapeSql(userName.trim()) + "%' ");
		}
		if (IConstants.DEFAULT_NUMERIC != borrowWay) {
			condition.append(" and borrowWay =" + borrowWay);
		}
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" v_t_borrow_h_flowmark a LEFT JOIN (SELECT userid,COUNT(1) AS counts FROM t_materialsauth where auditStatus = 3 GROUP BY userid) b ON a.userid=b.userid ",
					resultFeilds, " order by id desc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * add by houli 获得所有等待资料审核的借款
	 * 
	 * @return
	 * @throws Exception
	 * @throws DataException
	 */
	public List<Map<String, Object>> queryAllWaitingBorrow() throws Exception {
		Connection conn = MySQL.getConnection();
		List<Map<String, Object>> returnMap = new ArrayList<Map<String,Object>>();
		try {
			returnMap = borrowManageDao.queryAllWaitingBorrow(conn);
			conn.commit();
			return returnMap;
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: queryBorrowFlowMarkDetailById
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:24:35
	 * @Return:
	 * @Descb: 后台借款流标的借款详情
	 * @Throws:
	 */
	public Map<String, String> queryBorrowFlowMarkDetailById(long id)
			throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowFlowMarkDetailById(conn, id);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	/**
	 * @MethodName: queryBorrowAllByCondition
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:09:16
	 * @Return:
	 * @Descb: 查询后台借款管理中的借款记录
	 * @Throws:
	 */
	public void queryBorrowAllByCondition(Long id,String userName, int borrowWay,
			int borrowStatus, int borrowProduct,int agent,PageBean<Map<String, Object>> pageBean)
			throws Exception {
		String resultFeilds = " * , f_sjzd('productType',borrowProduct) borrowProductRename ," +
				" f_sjzd('borrowWayType', borrowWayYTF) borrowWayYTFRename ," +
				" CONCAT(annualRate ,'%')  annualRateRename ," + 
				" CASE WHEN isDayThe = 1 THEN CONCAT(deadline, '个月') ELSE CONCAT(deadline, '天') END AS deadlineRename ," +
				" CONCAT(raiseTerm ,'天')  raiseTermRename ," +
				" CONCAT(jbScore ,'分')  jbScoreRename ," +
				" CONCAT(xyScore ,'分')  xyScoreRename ," +
				" CONCAT(zcScore ,'分')  zcScoreRename ," +
				" CONCAT(allScore ,'分')  allScoreRename ," +
				" f_sjzd('borrowStatusType', borrowStatus) borrowStatusRename ," +
				" f_sjzd('paymentModeType', borrowWayYTF) paymentModeTypeRename ";
		StringBuffer condition = new StringBuffer();
		if (StringUtils.isNotBlank(userName)) {
			condition.append(" and username  like '%"
					+ StringEscapeUtils.escapeSql(userName.trim()) + "%' ");
		}
		if (IConstants.DEFAULT_NUMERIC != borrowWay) {
			condition.append(" and borrowWayYTF =" + borrowWay);
		}
		if (IConstants.DEFAULT_NUMERIC != borrowStatus) {
			condition.append(" and borrowStatus =" + borrowStatus);
		}
		if (IConstants.DEFAULT_NUMERIC != borrowProduct) {
			condition.append(" and borrowProduct =" + borrowProduct);
		}
		if (IConstants.DEFAULT_NUMERIC != id) {
			condition.append(" and id =" + id);
		}
		if (IConstants.DEFAULT_NUMERIC != agent) {
			condition.append(" and agent =" + agent);
		}
		
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" v_t_borrow_h a LEFT JOIN (SELECT userid,COUNT(1) AS counts FROM t_materialsauth where auditStatus = 3 GROUP BY userid) b ON a.userid=b.userid ",
					resultFeilds, " order by borrowStatus asc,id desc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}
	
	public Map<String,String> queryBorrowAllSumByCondition(Long id,String userName, int borrowWay,
			int borrowStatus, int borrowProduct,int agent)throws Exception {
		Map<String,String> map = new HashMap<String, String>();
		Connection conn = MySQL.getConnection();
		try {
			map = borrowManageDao.queryBorrowAllSumByCondition(conn, id, userName, borrowWay, borrowStatus,borrowProduct,agent);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return map;
	}
	/**
	 * @MethodName: queryBorrowTreatyByCondition
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:09:16
	 * @Return:
	 * @Descb: 查询后台借款管理中的借款记录给借款协议管理使用
	 * @Throws:
	 */
	public void queryBorrowTreatyByCondition(Long id,String userName, int borrowWay,
			int borrowStatus, int borrowProduct,PageBean<Map<String, Object>> pageBean)
			throws Exception {
		String resultFeilds = " * ";
		StringBuffer condition = new StringBuffer();
		if (StringUtils.isNotBlank(userName)) {
			condition.append(" and username  like '%"
					+ StringEscapeUtils.escapeSql(userName.trim()) + "%' ");
		}
		if (IConstants.DEFAULT_NUMERIC != borrowStatus) {
			condition.append(" and borrowStatus =" + borrowStatus);
		}else{
			condition.append(" and borrowStatus in (3,4,5) ");
		}
		if (IConstants.DEFAULT_NUMERIC != borrowWay) {
			condition.append(" and borrowWayYTF =" + borrowWay);
		}
		if (IConstants.DEFAULT_NUMERIC != borrowProduct) {
			condition.append(" and borrowProduct =" + borrowProduct);
		}
		if (IConstants.DEFAULT_NUMERIC != id) {
			condition.append(" and id =" + id);
		}
		
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" v_t_borrow_h a LEFT JOIN (SELECT userid,COUNT(1) AS counts FROM t_materialsauth where auditStatus = 3 GROUP BY userid) b ON a.userid=b.userid ",
					resultFeilds, " order by borrowStatus asc,id desc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: queryProductAllByCondition
	 * @Param: BorrowManageService
	 * @Author: sunbing
	 * @Date: 2014-7-1 下午10:09:16
	 * @Return:
	 * @Descb: 查询后台产品记录
	 * @Throws:
	 */
	public void queryProductAllByCondition(String productName, int productStatus,
			int productType,PageBean<Map<String, Object>> pageBean)
			throws Exception {
		String resultFeilds = " *  , f_sjzd('productType',type) typeRename ," +
							" CONCAT(productAnnualRate ,'%')  productAnnualRateRename ," +
							" CONCAT(schedules ,'%')  schedulesRename ," +
							" f_sjzd('productStatusType',productStatus) productStatusRename ";
		StringBuffer condition = new StringBuffer();
		if (StringUtils.isNotBlank(productName)) {
			condition.append(" and sn  like '%"
					+ StringEscapeUtils.escapeSql(productName.trim()) + "%' ");
		}
		if (IConstants.DEFAULT_NUMERIC != productStatus) {
			condition.append(" and productStatus =" + productStatus);
		}
		if (IConstants.DEFAULT_NUMERIC != productType) {
			condition.append(" and type =" + productType);
		}
		
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" v_t_product ",
					resultFeilds, " order by pid desc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}
	public void queryProductDetail(long pid,PageBean<Map<String, Object>> pageBean)
			throws Exception {
		String resultFeilds = " * ";
		StringBuffer condition = new StringBuffer();
		
		if (IConstants.DEFAULT_NUMERIC != pid) {
			condition.append(" and pid =" + pid);
		}
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" v_t_product_borrow ",
					resultFeilds, " order by bid desc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
	}
	public void queryInvestDetailByParentBId(long parentBId,PageBean<Map<String, Object>> pageBean)
		throws Exception {
	String resultFeilds = " * ";
	StringBuffer condition = new StringBuffer();
	
	if (IConstants.DEFAULT_NUMERIC != parentBId) {
		condition.append(" and parentBId =" + parentBId);
	}
	Connection conn = MySQL.getConnection();
	try {
		dataPage(
				conn,
				pageBean,
				" v_t_borrow_investrecord ",
				resultFeilds, " order by id desc", condition.toString());
		conn.commit();
	} catch (Exception e) {
		log.error(e);
		e.printStackTrace();
		conn.rollback();
		throw e;
	} finally {
		conn.close();
	}
	}
	
	public void queryInvestDetail(long pid,PageBean<Map<String, Object>> pageBean)
		throws Exception {
	String resultFeilds = " * ";
	StringBuffer condition = new StringBuffer();
	
	if (IConstants.DEFAULT_NUMERIC != pid) {
		condition.append(" and productId =" + pid);
	}
	Connection conn = MySQL.getConnection();
	try {
		dataPage(
				conn,
				pageBean,
				" v_t_borrow_investrecord ",
				resultFeilds, " order by id desc", condition.toString());
		conn.commit();
	} catch (Exception e) {
		log.error(e);
		e.printStackTrace();
		conn.rollback();
		throw e;
	} finally {
		conn.close();
	}
	}
	public void queryChildrenBorrowByPid(long pid,PageBean<Map<String, Object>> pageBean)
			throws Exception {
		String resultFeilds = " * ";
		StringBuffer condition = new StringBuffer();
		
		if (IConstants.DEFAULT_NUMERIC != pid) {
			condition.append(" and parentBId =" + pid);
		}
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" t_borrow ",
					resultFeilds, " order by id desc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: queryBorrowAllDetailById
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:24:35
	 * @Return:
	 * @Descb: 后台借款的借款详情
	 * @Throws:
	 */
	public Map<String, String> queryBorrowAllDetailById(long id)
			throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowAllDetailById(conn, id);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}
	
	/**
	 * @MethodName: queryBorrowAllDetailById
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-10 下午10:24:35
	 * @Return:
	 * @Descb: 后台借款的借款
	 * @Throws:
	 */
	public Map<String, String> queryBorrowById(long id)
			throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowById(conn, id);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}
	
	/**
	 * @throws DataException
	 * @MethodName: updateBorrowFistAuditStatus
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-13 下午01:19:48
	 * @Return:
	 * @Descb: 更新待发布的借款状态
	 * @Throws:
	 */
	public Long updateBorrowFistAuditStatus(long id, long reciver, int status,
			String msg, String auditOpinion, long sender, String basePath)
			throws Exception {
		Long result = -1L;
		DataSet ds = new DataSet();
		List<Object> outParameterValues = new ArrayList<Object>();
		Map<String, String> map_ret = new HashMap<String, String>();
		Map<String, String> adminMap = new HashMap<String, String>();
		Connection conn = MySQL.getConnection();
		// 得到管理员信息
		adminMap = adminDao.queryAdminById(conn, sender);
		if (status == IConstants.BORROW_STATUS_2) {

			try {
				Procedures.p_borrow_audit(conn, ds, outParameterValues, id,
						sender, status, msg, auditOpinion, basePath,
						new Date(), 0, "");
				map_ret.put("out_ret", outParameterValues.get(0) + "");
				map_ret.put("out_desc", outParameterValues.get(1) + "");
				result = Convert.strToLong(outParameterValues.get(0) + "", -1);
				if (result < 1) {
					conn.rollback();
					return -1L;
				}
				// 添加操作日志
				operationLogDao.addOperationLog(conn, "t_borrow", Convert
						.strToStr(adminMap.get("userName"), ""),
						IConstants.UPDATE, Convert.strToStr(adminMap
								.get("lastIP"), ""), 0, "初审通过", 2);
				conn.commit();
			} catch (Exception e) {
				log.error(e);
				e.printStackTrace();
				conn.rollback();
				throw e;
			} finally {
				conn.close();
			}
		} else {
			conn.close();
			// 撤消待发布的借款
			result = reBackBorrowFistAudit(id, sender, basePath, msg,
					auditOpinion);
			// Procedures.p_borrow_cancel(conn, ds, outParameterValues, id,
			// sender, status, auditOpinion, basePath, 0, "");
			// map_ret.put("out_ret", outParameterValues.get(0)+"");
			// map_ret.put("out_desc", outParameterValues.get(1)+"");
			// 添加操作日志
			// operationLogDao.addOperationLog(conn, "t_borrow",
			// Convert.strToStr(adminMap.get("userName"), ""),
			// IConstants.UPDATE, Convert.strToStr(adminMap.get("lastIP"), ""),
			// 0, "管理员撤销借款", 2);
		}
		return result;
	}

	/**
	 * @throws DataException
	 * @MethodName: updateBorrowTenderInStatus
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-13 下午01:20:27
	 * @Return:
	 * @Descb: 更新招标中的借款状态
	 * @Throws:
	 */
	public Long updateBorrowTenderInStatus(long id, String auditOpinion)
			throws Exception {
		Connection conn = MySQL.getConnection();

		Long result = -1L;
		try {
			result = borrowManageDao.updateBorrowTenderInStatus(conn, id,
					auditOpinion);
			if (result <= 0) {
				conn.rollback();
				return -1L;
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return result;
	}

	/**
	 * @throws Exception
	 * @throws DataException
	 * @throws Exception
	 * @MethodName: reBackBorrowTenderIn
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-13 下午08:40:22
	 * @Return:
	 * @Descb: 撤消借款
	 * @Throws:
	 */
	public long reBackBorrow(long id, long aId, String basePath)
			throws Exception {
		Connection conn = MySQL.getConnection();
		long returnId = -1;
		ContextLoader.getCurrentWebApplicationContext().getServletContext()
				.getAttribute(
						IInformTemplateConstants.INFORM_TEMPLATE_APPLICATION);
		DataSet ds = new DataSet();
		List<Object> outParameterValues = new ArrayList<Object>();
		Map<String, String> map_ret = new HashMap<String, String>();
		Map<String, String> adminMap = new HashMap<String, String>();
		try {
			Procedures.p_borrow_cancel(conn, ds, outParameterValues, id, aId,
					6, "", basePath, -1, "");
			map_ret.put("out_ret", outParameterValues.get(0) + "");
			map_ret.put("out_desc", outParameterValues.get(1) + "");
			returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			if (returnId < 1) {
				conn.rollback();
				return -1L;
			}
			// 添加操作日志
			adminMap = adminDao.queryAdminById(conn, aId);
			operationLogDao.addOperationLog(conn, "t_borrow", Convert.strToStr(
					adminMap.get("userName"), ""), IConstants.UPDATE, Convert
					.strToStr(adminMap.get("lastIP"), ""), 0, "管理员撤销借款", 2);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			return -1L;
		} finally {
			conn.close();
		}
		return returnId;
	}

	/**
	 * @throws Exception
	 * @MethodName: updateBorrowFullScaleStatus
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-13 下午01:21:09
	 * @Return:
	 * @Descb: 更新满标的借款状态
	 * @Throws:
	 */
	@SuppressWarnings("unchecked")
	public Map<String, String> updateBorrowFullScaleStatus(long id,
			long status, String auditOpinion, long adminId, String basePath)
			throws Exception {
		Connection conn = MySQL.getConnection();
		
		String identify = id + "_" + System.currentTimeMillis() + "";
		long ret = -1;
		DataSet ds = new DataSet();
		Map<String, String> map = new HashMap<String, String>();
		List<Object> outParameterValues = new ArrayList<Object>();
		List<Object> outParameters = new ArrayList<Object>();

		try {
			//校验审核处理
			Procedures.p_borrow_auth_fullscale(conn, ds, outParameterValues,
					id, status, -1, "", new BigDecimal(0.00), new BigDecimal(
							0.00), 0, 0, 0);
			ret = Convert.strToLong(outParameterValues.get(0) + "", -1);
			if (ret <= 0) {
				map.put("ret", ret + "");
				map.put("ret_desc", outParameterValues.get(1) + "");
				conn.rollback();
				return map;
			}
			//ret=4审核通过
			if (ret == 4) {
				double borrowAmount = Convert.strToDouble(outParameterValues.get(2)+ "", 0);
				double annualRate = Convert.strToDouble(outParameterValues.get(3)+ "", 0);
				int deadline = Convert.strToInt(outParameterValues.get(4) + "",0);
				int isDayThe = Convert.strToInt(outParameterValues.get(5) + "",1);
				int paymentMode = Convert.strToInt(outParameterValues.get(6)+ "", 1);

				//生成还款记录
				List<Map<String, Object>> repayMapList = getRepayList(borrowAmount, annualRate, deadline,
						isDayThe, paymentMode);
				
				//添加预还款记录
				ret = addPreRepay(id, conn, identify, ret, repayMapList);

				if (ret <= 0) {
					map.put("ret", ret + "");
					map.put("ret_desc", "添加预还款记录执行失败");
					conn.rollback();
					return map;
				}	
			}
			//满标审核处理
			Procedures.p_borrow_deal_fullscale(conn, ds, outParameters, id,
					adminId, status, new Date(), auditOpinion, identify,
					basePath, -1, "");
			ret = Convert.strToLong(outParameters.get(0) + "", -1);
			if (ret > 0 && status == 4) {
				//添加系统操作日志
				 Map<String, String> adminMap = adminDao.queryAdminById(conn, adminId);
				 operationLogDao.addOperationLog(conn, "t_borrow", Convert
						.strToStr(adminMap.get("userName"), ""),
						IConstants.UPDATE, Convert.strToStr(adminMap
								.get("lastIP"), ""), 0, "满标审核通过", 2);

			}
			map.put("ret", ret + "");
			map.put("ret_desc", outParameters.get(1) + "");
			if (ret <= 0) {
				conn.rollback();
			} else {
				conn.commit();
			}

		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return map;
	}
	
	/**
	 * @Return:
	 * @Descb: 分标计息
	 * @Throws:
	 */
	public Map<String, String> createChildrenBorrow(long bid) throws Exception {
		Connection conn = MySQL.getConnection();
		long ret = -1;
		DataSet ds = new DataSet();
		Map<String, String> map = new HashMap<String, String>();
		List<Object> outParameterValues = new ArrayList<Object>();

		try {
			Procedures.p_create_children_borrow(conn, ds, outParameterValues,bid, 0, "");
			ret = Convert.strToLong(outParameterValues.get(0) + "", -1);
			map.put("ret", ret + "");
			map.put("ret_desc", outParameterValues.get(1) + "");
			if (ret <= 0) {
				conn.rollback();
				return map;
			}
			conn.commit();

		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return map;
	}
	
	/**
	 * @Return:
	 * @Descb: 发布产品
	 * @Throws:
	 */
	public Map<String, String> publishProductInit() throws Exception {
		Connection conn = MySQL.getConnection();
		long ret = -1;
		DataSet ds = new DataSet();
		Map<String, String> map = new HashMap<String, String>();
		List<Object> outParameterValues = new ArrayList<Object>();

		try {
			Procedures.p_create_borrow_product(conn, ds, outParameterValues, 0, "");
			ret = Convert.strToLong(outParameterValues.get(0) + "", -1);
			map.put("ret", ret + "");
			map.put("ret_desc", outParameterValues.get(1) + "");
			if (ret <= 0) {
				conn.rollback();
				return map;
			}
			conn.commit();

		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	private long addPreRepay(long id, Connection conn, String identify,
			long ret, List<Map<String, Object>> repayMapList)
			throws SQLException {
		int count = 1;
		for (Map<String, Object> paymentMap : repayMapList) {
			String repayPeriod = paymentMap.get("repayPeriod") + "";// 还款期数
			double stillPrincipal = Convert.strToDouble(paymentMap.get("stillPrincipal")+ "", 0);// 应还本金
			double stillInterest = Convert.strToDouble(paymentMap.get("stillInterest")+ "", 0);// 应还利息
			double principalBalance = Convert.strToDouble(paymentMap.get("principalBalance")+ "", 0);// 剩余本金
			double interestBalance = Convert.strToDouble(paymentMap.get("interestBalance")+ "", 0);// 剩余利息
			double totalSum = Convert.strToDouble(paymentMap.get("totalSum")+ "", 0);// 本息余额
			double totalAmount = Convert.strToDouble(paymentMap.get("totalAmount")+ "", 0);// 还款总额
			double mRate = Convert.strToDouble(paymentMap.get("mRate") + "", 0);// 月利率
			String repayDate = paymentMap.get("repayDate") + "";
			
			ret = repamentDao.addPreRepament(conn, id, identify,
					repayPeriod, stillPrincipal, stillInterest,
					principalBalance, interestBalance, totalSum,
					totalAmount, mRate, repayDate, count);
			count++;
			if (ret <= 0) {
				break;
			}
		}
		return ret;
	}

	private List<Map<String, Object>> getRepayList(double borrowAmount,
			double annualRate, int deadline, int isDayThe, int paymentMode) {
		List<Map<String, Object>> repayMapList = null;
		AmountUtil au = new AmountUtil();
		if (paymentMode == 1) {
			// 按月等额还款
			repayMapList = au.rateCalculateMonth(borrowAmount,
					annualRate, deadline, isDayThe);
		} else if (paymentMode == 2) {
			// 先息后本还款
			repayMapList = au.rateCalculateSum(borrowAmount,
					annualRate, deadline, isDayThe);
		} else if (paymentMode == 3) {
			// 秒还还款
			repayMapList = au.rateSecondsSum(borrowAmount, annualRate,
					deadline);
		}// 一次性还款
		else if (paymentMode == 4) {
			repayMapList = au.rateCalculateOne(borrowAmount,
					annualRate, deadline, isDayThe);
		}
		return repayMapList;
	}
	
	public SelectedService getSelectedService() {
		return selectedService;
	}

	public void setSelectedService(SelectedService selectedService) {
		this.selectedService = selectedService;
	}

	public AwardService getAwardService() {
		return awardService;
	}

	public void setAwardService(AwardService awardService) {
		this.awardService = awardService;
	}

	public long reBackBorrowFistAudit(long idLong, Long id, String basePath,
			String msg, String auditOpinion) throws Exception {
		Connection conn = MySQL.getConnection();
		long returnId = -1;
		DataSet ds = new DataSet();
		List<Object> outParameterValues = new ArrayList<Object>();
		Map<String, String> map_ret = new HashMap<String, String>();
		Map<String, String> adminMap = new HashMap<String, String>();
		try {
			Procedures.p_borrow_cancel(conn, ds, outParameterValues, idLong,
					id, 6, auditOpinion, basePath, -1, "");
			map_ret.put("out_ret", outParameterValues.get(0) + "");
			map_ret.put("out_desc", outParameterValues.get(1) + "");
			returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			if (returnId <= 0) {
				conn.rollback();
				return Convert.strToLong(map_ret.get("out_ret"), -1);
			}
			// 添加操作日志
			adminMap = adminDao.queryAdminById(conn, id);
			operationLogDao.addOperationLog(conn, "t_borrow", Convert.strToStr(
					adminMap.get("userName"), ""), IConstants.UPDATE, Convert
					.strToStr(adminMap.get("lastIP"), ""), 0, "管理员撤销借款", 2);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return Convert.strToLong(map_ret.get("out_ret"), 1);
	}

	/**
	 * @MethodName: addCirculationRepay
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-7-23 下午04:32:03
	 * @Return:
	 * @Descb: 添加流转标还款记录
	 * @Throws:
	 */
	public long addCirculationRepay(long repayId, double amountDouble, Long id,
			String remark) throws Exception {
		Connection conn = MySQL.getConnection();
		long returnId = -1;
		try {
			returnId = repaymentRecordDao.addRepayMentRecord(conn, repayId,
					amountDouble, id, remark);
			if (returnId <= 0) {
				conn.rollback();
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return returnId;
	}

	public Map<String, String> queryBorrowInfo(long idLong) throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowInfo(conn, idLong);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;

	}

	/**
	 * 查看借款协议中的内容
	 * 
	 * @param borrowId
	 * @return
	 * @throws Exception
	 * @throws DataException
	 */
	public Map<String, String> queryBorrowMany(long borrowId) throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = investDao.queryBorrowMany(conn, borrowId);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	/**
	 * 根据借款id 和投资id 查询
	 * 
	 * @param borrowId
	 * @param invest_id
	 * @return
	 * @throws Exception
	 * @throws DataException
	 */
	public List<Map<String, Object>> queryInvestMomey(long borrowId,
			long invest_id) throws Exception {
		Connection conn = MySQL.getConnection();
		List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();
		try {
			map = investDao.queryInvestMomey(conn, invest_id, borrowId);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	/**
	 * 查询所有投资人信息
	 * 
	 * @param borrowId
	 * @return
	 * @throws Exception
	 * @throws DataException
	 */
	public List<Map<String, Object>> queryUsername(long borrowId, long invest_id)
			throws Exception {
		Connection conn = MySQL.getConnection();
		List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();
		try {
			map = investDao.queryUsername(conn, borrowId, invest_id);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	/**
	 * 根据借款查询借款应还的金额
	 * 
	 * @param conn
	 * @param borrowId
	 * @return
	 * @throws Exception
	 * @throws DataException
	 */
	public Map<String, String> queryBorrowSumMomeny(long borrowId,
			long invest_id) throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = investDao.queryBorrowSumMomeny(conn, borrowId, invest_id);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;

	}

	// 借款管理模块中，查询各个报表的总额
	public Map<String, String> queryBorrowTotalFistAuditDetail()
			throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowTotalFistAuditDetail(conn);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	public Map<String, String> queryBorrowTotalWait() throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowTotalWait(conn);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	public Map<String, String> queryBorrowTotalTenderDetail() throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowTotalTenderDetail(conn);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	public Map<String, String> queryBorrowFlowMarkDetail() throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowFlowMarkDetail(conn);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	public Map<String, String> queryBorrowTotalFullScaleDetail()
			throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryBorrowTotalFullScaleDetail(conn);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	public InvestDao getInvestDao() {
		return investDao;
	}

	public void setInvestDao(InvestDao investDao) {
		this.investDao = investDao;
	}

	public BorrowManageDao getBorrowManageDao() {
		return borrowManageDao;
	}

	public void setBorrowManageDao(BorrowManageDao borrowManageDao) {
		this.borrowManageDao = borrowManageDao;
	}

	public void setAccountUsersDao(AccountUsersDao accountUsersDao) {
		this.accountUsersDao = accountUsersDao;
	}

	public RepamentDao getRepamentDao() {
		return repamentDao;
	}

	public void setRepamentDao(RepamentDao repamentDao) {
		this.repamentDao = repamentDao;
	}

	public BorrowDao getBorrowDao() {
		return borrowDao;
	}

	public void setBorrowDao(BorrowDao borrowDao) {
		this.borrowDao = borrowDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setFundRecordDao(FundRecordDao fundRecordDao) {
		this.fundRecordDao = fundRecordDao;
	}

	public void setRepaymentRecordDao(RepaymentRecordDao repaymentRecordDao) {
		this.repaymentRecordDao = repaymentRecordDao;
	}

	public AdminDao getAdminDao() {
		return adminDao;
	}

	public void setAdminDao(AdminDao adminDao) {
		this.adminDao = adminDao;
	}

	public PlatformCostService getPlatformCostService() {
		return platformCostService;
	}

	public void setPlatformCostService(PlatformCostService platformCostService) {
		this.platformCostService = platformCostService;
	}

	public AccountUsersDao getAccountUsersDao() {
		return accountUsersDao;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public FundRecordDao getFundRecordDao() {
		return fundRecordDao;
	}

	public RepaymentRecordDao getRepaymentRecordDao() {
		return repaymentRecordDao;
	}

	public NoticeTaskDao getNoticeTaskDao() {
		return noticeTaskDao;
	}

	public void setNoticeTaskDao(NoticeTaskDao noticeTaskDao) {
		this.noticeTaskDao = noticeTaskDao;
	}

	public OperationLogDao getOperationLogDao() {
		return operationLogDao;
	}

	public void setOperationLogDao(OperationLogDao operationLogDao) {
		this.operationLogDao = operationLogDao;
	}

	public Map<String, String> queryAuthProtocol(long borrowId, long investId) throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowManageDao.queryAuthProtocol(conn,borrowId,investId);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}
	 /** 
     * 发布借款信息
     * @param id
     * @param borrowStatus
     * @return
     * @throws SQLException [参数说明]
     * 
     * @return long [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public long updateReleased(String id)
        throws SQLException
    {
        Connection conn = MySQL.getConnection();
        
        String[] ids = id.split(",");
        long result = -1L;
        try
        {
            for (int i = 0; i < ids.length; i++)
            {
                result = borrowManageDao.updateReleased(conn, ids[i]);
            }
            conn.commit();
        }
        catch (SQLException e)
        {
            log.error(e);
            conn.rollback();
            e.printStackTrace();
            throw e;
        }
        finally
        {
            conn.close();
        }
        return result;
    }
    /**
     * 根据ID查询借款信息--初审
     * 
     * @param id
     * @return
     * @throws SQLException
     * @throws DataException
     *             [参数说明]
     * 
     * @return Map<String,String> [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public Map<String, String> queryRecheckById(String id)
        throws SQLException, DataException
    {
        Connection conn = connectionManager.getConnection();
        Map<String, String> map = new HashMap<String, String>();
        try
        {
            map = borrowManageDao.queryRecheckById(conn, id);
        }
        catch (SQLException e)
        {
            log.error(e);
            e.printStackTrace();
            throw e;
        }
        catch (DataException e)
        {
            log.error(e);
            e.printStackTrace();
            throw e;
        }
        finally
        {
            conn.close();
        }
        return map;
    }
	 /** 
     * 定时
     * @param id
     * @param times
     * @return
     * @throws SQLException [参数说明]
     * 
     * @return long [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public long updateTimer(String id, String times)
        throws SQLException
    {
        Connection conn = MySQL.getConnection();
        
        String[] ids = id.split(",");
        long result = -1L;
        try
        {
            for (int i = 0; i < ids.length; i++)
            {
                result = borrowManageDao.updateTimer(conn, ids[i], times);
            }
            conn.commit();
        }
        catch (SQLException e)
        {
            log.error(e);
            conn.rollback();
            e.printStackTrace();
            throw e;
        }
        finally
        {
            conn.close();
        }
        return result;
    }
    /**
	 * @throws DataException
	 * @MethodName: updateBorrowRiskAssess
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-13 下午01:20:27
	 * @Return:
	 * @Descb: 更新待发布的借款风险评定内容
	 * @Throws:
	 */
	public Long updateBorrowRiskAssess(long id, String riskAssess)
			throws Exception {
		Connection conn = MySQL.getConnection();

		Long result = -1L;
		try {
			result = borrowManageDao.updateBorrowRiskAssess(conn, id,
					riskAssess);
			if (result <= 0) {
				conn.rollback();
				return -1L;
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return result;
	}

    /**
	 * @throws DataException
	 * @MethodName: updateBorrowTenderInStatus
	 * @Param: BorrowManageService
	 * @Author: gang.lv
	 * @Date: 2013-3-13 下午01:20:27
	 * @Return:
	 * @Descb: 更新待发布的借款风险级别
	 * @Throws:
	 */
	public Long updateBorrowRiskLevel(String ids,int jbScore,int xyScore,int zcScore,int allScore)
			throws Exception {
		Connection conn = MySQL.getConnection();

		Long result = -1L;
		try {
			result = borrowManageDao.updateBorrowRiskLevel(conn, ids,
					jbScore, xyScore, zcScore, allScore);
			if (result <= 0) {
				conn.rollback();
				return -1L;
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return result;
	}
	
	public Long updateBorrow(Map<String, String> paramMap) throws Exception {
		Connection conn = MySQL.getConnection();

		Long result = -1L;
		try {
			result = borrowDao.updateBorrow(conn,paramMap );
			if (result <= 0) {
				conn.rollback();
				return -1L;
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return result;
	}
	
	public Long delPublishBorrow(long id) throws Exception {
		Connection conn = MySQL.getConnection();
		Long result = -1L;
		try {
			result = borrowDao.delPublishBorrow(conn,id );
			if (result <= 0) {
				conn.rollback();
				return -1L;
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return result;
	}
	
	/**
	 * @MethodName: queryYebAssignmentDebtByCondition
	 * @Param: BorrowManageService
	 * @Author: sunbing
	 * @Date: 2014-7-1 下午10:09:16
	 * @Return:
	 * @Descb: 查询余额宝赎回记录
	 * @Throws:
	 */
	public void queryYebAssignmentDebtByCondition(String oriSN,String userName, int debtStatus,String applyTimeStart, String applyTimeEnd
			, String dealTimeStart, String dealTimeEnd,PageBean<Map<String, Object>> pageBean)
			throws Exception {
		String resultFeilds = " * , f_sjzd('debtStatusType',debtStatus) debtStatusRename ,"+
							" f_sjzd('isWebsiteType', isWebsite) isWebsiteRename ";
		StringBuffer condition = new StringBuffer();
		if (StringUtils.isNotBlank(oriSN)) {
			condition.append(" and oriSN  like '%"
					+ StringEscapeUtils.escapeSql(oriSN.trim()) + "%' ");
		}
		if (StringUtils.isNotBlank(userName)) {
			condition.append(" and username  like '%"
					+ StringEscapeUtils.escapeSql(userName.trim()) + "%' ");
		}
		if (debtStatus>0) {
			condition.append(" and debtStatus  ='"
					+ debtStatus + "'");
		}
		if (StringUtils.isNotBlank(applyTimeStart)) {
			condition.append(" and applyTime >='"
					+ StringEscapeUtils.escapeSql(applyTimeStart) + "'");
		}
		if (StringUtils.isNotBlank(applyTimeEnd)) {
			condition.append(" and applyTime <='"
					+ StringEscapeUtils.escapeSql(applyTimeEnd) + "'");
		}
		if (StringUtils.isNotBlank(dealTimeStart)) {
			condition.append(" and dealTime >='"
					+ StringEscapeUtils.escapeSql(dealTimeStart) + "'");
		}
		if (StringUtils.isNotBlank(dealTimeEnd)) {
			condition.append( " and dealTime <='"
					+ StringEscapeUtils.escapeSql(dealTimeEnd) + "'");
		}
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" v_t_yeb_assignment_debt ",
					resultFeilds, " order by id desc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}
	public Map<String,String> queryYebAssignmentDebtSumByCondition(String oriSN, String userName, int debtStatus, String applyTimeStart, String applyTimeEnd
			, String dealTimeStart, String dealTimeEnd)
			throws Exception {
		Map<String,String> map = new HashMap<String, String>();
		Connection conn = MySQL.getConnection();
		try {
			map = borrowManageDao.queryYebAssignmentDebtSumByCondition(conn, oriSN, userName, debtStatus, applyTimeStart, applyTimeEnd, dealTimeStart, dealTimeEnd);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();

			throw e;
		} finally {
			conn.close();
		}
		return map;
	}
	/**
	 * @MethodName: queryOtherAssignmentDebtByCondition
	 * @Param: BorrowManageService
	 * @Author: sunbing
	 * @Date: 2014-7-1 下午10:09:16
	 * @Return:
	 * @Descb: 查询赎回记录
	 * @Throws:
	 */
	public void queryOtherAssignmentDebtByCondition(String SN, int borrowProduct,String applyTimeStart, String applyTimeEnd
			, String dealTimeStart, String dealTimeEnd, int debtStatus, PageBean<Map<String, Object>> pageBean)
			throws Exception {
		String resultFeilds = " * , f_sjzd('productType',borrowProduct) borrowProductRename ,"+
							  " f_sjzd('debtStatusType',debtStatus) debtStatusRename ,"+
							  " CONCAT(discount ,'%')  discountRename ,"+
							  " CONCAT(annualRate ,'%')  annualRateRename ,"+
							  " CONCAT(realAnnualRate ,'%')  realAnnualRateRename ,"+
							  " CASE WHEN borrowProduct = 4 THEN borrowNumber ELSE SN END AS SNRename, "+
							  " CASE WHEN debtStatus = 3 THEN investorUsername ELSE '' END AS investorUsernameRename ";
		StringBuffer condition = new StringBuffer();
		if (StringUtils.isNotBlank(SN)) {
			condition.append(" and ( SN  like '%"
					+ StringEscapeUtils.escapeSql(SN.trim()) + "%' or borrowNumber like '%"
					+ StringEscapeUtils.escapeSql(SN.trim()) + "%') ");
		}
		if (borrowProduct>0) {
			condition.append(" and borrowProduct  ='"
					+ borrowProduct + "'");
		}
		if (StringUtils.isNotBlank(applyTimeStart)) {
			condition.append(" and applyTime >='"
					+ StringEscapeUtils.escapeSql(applyTimeStart) + "'");
		}
		if (StringUtils.isNotBlank(applyTimeEnd)) {
			condition.append(" and applyTime <='"
					+ StringEscapeUtils.escapeSql(applyTimeEnd) + "'");
		}
		if (StringUtils.isNotBlank(dealTimeStart)) {
			condition.append(" and dealTime >='"
					+ StringEscapeUtils.escapeSql(dealTimeStart) + "'");
		}
		if (StringUtils.isNotBlank(dealTimeEnd)) {
			condition.append( " and dealTime <='"
					+ StringEscapeUtils.escapeSql(dealTimeEnd) + "'");
		}
		if (debtStatus>0) {
			condition.append(" and debtStatus  ='"
					+ debtStatus + "'");
		}
		Connection conn = MySQL.getConnection();
		try {
			dataPage(
					conn,
					pageBean,
					" v_t_assignment_debt ",
					resultFeilds, " order by id desc", condition.toString());
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
	}
	
	
	/**
	 * @MethodName: isExistsAnnualRateByProductType
	 * @Param: BorrowManageService
	 * @Return:
	 * @Descb: 判断未发布的借款标的利率是否一致
	 * @Throws:
	 */
	public long isExistsAnnualRateByProductType(String borrowProduct, String annualRate) throws Exception {
		Connection conn = MySQL.getConnection();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = borrowDao.isExistsAnnualRateByProductType(conn, borrowProduct, annualRate);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} finally {
			conn.close();
		}
		return list.size() <= 0 ? -1L : 1L;
	}

	public Map<String, String> queryYebAnnualrateId() throws Exception{
		// TODO Auto-generated method stub
		Connection conn = MySQL.getConnection();
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowDao.queryYebAnnualrateId(conn);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}

	public Map<String, String> queryYebAnnualrateSet(int id) throws Exception{
		// TODO Auto-generated method stub
		Connection conn = MySQL.getConnection();

		Map<String, String> map = new HashMap<String, String>();
		try {
			map = borrowDao.queryYebAnnualrateSet(conn, id);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}
	public long updateYebAnnualrateSet(int id) throws Exception{
		// TODO Auto-generated method stub
		Connection conn = MySQL.getConnection();
		Long result = -1L;
		try {
			result = borrowDao.updateYebAnnualrateSet(conn, id);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return result;
	}

	public Long addUserYebAnnualrateSet(String annualRate, int status, Long operatorId,
			String operatTime) throws Exception{
		// TODO Auto-generated method stub
		Connection conn = MySQL.getConnection();
		Long result = -1L;
		try {
			result = borrowDao.addYebAnnualrateSet(conn, annualRate, status, operatorId, operatTime);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return result;
	}
	
	public Long updateBorrowPublisherUsername(String username,long borrowId) throws Exception {
		Connection conn = MySQL.getConnection();

		Long result = -1L;
		try {
			result = borrowDao.updateBorrowPublisherUsername(conn,username,borrowId );
			if (result <= 0) {
				conn.rollback();
				return -1L;
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();

			throw e;
		} finally {
			conn.close();
		}
		return result;
	}
	
	public void queryInfoDisclosure(PageBean<Map<String, Object>> pageBean, Long bid)
	throws Exception {
		Connection conn = MySQL.getConnection();
		StringBuffer condition = new StringBuffer();
		if (bid>0) {
			condition.append(" and bid  ='"
					+ bid + "'");
		}
		try {
			dataPage(conn, pageBean, "t_infodisclosure", "*",
					" order by bid desc,orderShort asc ", condition.toString());
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} finally {
			conn.close();
		}
	}
	public Long addInfoDisclosure(Long bid, String img, Long orderShort)
			throws Exception {
		Connection conn = MySQL.getConnection();
		Long commonId = -1L;
		Long newsId = -1L;
		try {
			commonId = borrowManageDao.addInfoDisclosure(conn, bid, img, orderShort);
			if (commonId < 0) {// 如果小于0，添加失败，回滚
				conn.rollback();
			}else{
				newsId = 1L;
			}
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			log.error(e);
			e.printStackTrace();
			throw e;
		} finally {
			conn.close();
		}
		return newsId;
	}
	public Map<String, String> queryInfoDisclosureById(long id) throws Exception {
		Connection conn = MySQL.getConnection();
		Map<String, String> map = null;
		try {
			map = borrowManageDao.queryInfoDisclosureById(conn, id);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			
			throw e;
		} finally {
			conn.close();
		}
		return map;
	}
	
	public Long updateInfoDisclosure(Long id, Long bid, String img, Long orderShort)
		throws Exception {
		Connection conn = MySQL.getConnection();
		try {
			borrowManageDao.updateInfoDisclosure(conn, id, bid, img, orderShort);
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			log.error(e);
			e.printStackTrace();
			throw e;
		} finally {
			conn.close();
		}
		return 1L;
	}
	public Long deleteInfoDisclosure(String commonIds) throws Exception,
		DataException {
		Long result = -1L;
		Connection conn = MySQL.getConnection();
		try {
			result = borrowManageDao.deleteInfoDisclosure(conn, commonIds);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			
			throw e;
		} finally {
			conn.close();
		}
		return result;
	}
}
